﻿using Quartz;
using RCS.Config;
using Seer.SeerSocket;



[DisallowConcurrentExecution]
public class DetectAgvJob : IJob
{
    private readonly ILogger<DetectAgvJob> logger;
    private readonly SqliteDbContext ctx;
    private readonly IServiceScope serviceScope;
    private readonly Dictionary<string, SeerSocket> seerSockets;
    private readonly IConfiguration configuration;


    public DetectAgvJob(ILogger<DetectAgvJob> logger, IServiceScopeFactory scopeFactory, IConfiguration configuration)
    {
        this.serviceScope = scopeFactory.CreateScope();
        var sp = serviceScope.ServiceProvider;
        this.ctx = sp.GetRequiredService<SqliteDbContext>();
        this.logger = sp.GetRequiredService<ILogger<DetectAgvJob>>();
        this.seerSockets = sp.GetRequiredService<Dictionary<string, SeerSocket>>();
        this.logger = logger;
        this.configuration = configuration;
    }




    public async Task Execute(IJobExecutionContext context)
    {
        await this.DetectBatteryJob();
    }



#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
    private async Task DetectBatteryJob()
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
    {
        try
        {

            var configurationSection = configuration.GetSection("CacheJson");
            var options = new AgvCacheJsonOptions();
            configurationSection.Bind(options);
            if (string.IsNullOrEmpty(options.AgvJsonFolder)) throw new ConfigurationException("AGV的Json Folder为空");

            foreach (KeyValuePair<string, SeerSocket> pair in this.seerSockets)
            {
                var msg = pair.Value.Send(0x044c);
                if (msg == "fail")
                {
                    Console.WriteLine($"{pair.Key}: 断开连接");
                    continue;
                }
                string jsonCachePath = Path.Combine(options.AgvJsonFolder, pair.Key + ".json");
                using StreamWriter writer = new StreamWriter(jsonCachePath);
                writer.Write(msg);
            }

        }
        catch (Exception exception)
        {
            Console.WriteLine($"{DateTime.Now} : {exception}");
        }
    }

}


